#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>

#define CTL_BIT             (1 << 8)
#define DATA_NUMBER         (0x7F)

int fd_input;
int fd_output;
int size = 0;

void ctl_bit_set(char *input, char *output)
{
    static int times = 5;
    int i = 0;
    char number = 0;
    char data;
    number = input[0];
    number = (char)(DATA_NUMBER & number);
    data = input[1];
    for(i = 0; i < number; ++i)
        write(fd_output, &data, 1);

    if (times != 0 ){
        printf("data = %x\n", data);
        printf("number = %x\n", number);
        times--;
    }
}
void only_trans_data(char *input, char *output, int *counts)
{
    static int times = 5;
    int i = 0;
    char number = 0;
    char buffer[127] = {0};
    number = *input++;
    for( i = 0; i < number; ++i) 
        buffer[i] = *input++;
    write(fd_output, buffer, number);
    *counts = (number + 1); 

    if (times != 0 ){
        printf("only number = %d\n", number);
        printf("only counts = %d\n", *counts);
        times--;
    }
}
void unrle(char *input, char *output)
{
    int i = 0;
    int counts = 0;
    size -= 4;
    input = input+4;

    printf("size = %d\n", size);
    for ( i = 0 ; i < size ;){
        if( *input & CTL_BIT ){
            ctl_bit_set(input, output);
            input += 2;
            i += 2;
        }
        else{
            only_trans_data(input, output, &counts);
            input += counts;
            i += counts;
        }
    }
}

int main(int argc, char *argv[])
{
    char input[1024*400];
    char output[1024*400];
    int fd_read_input;
    struct stat st;
    fd_input = open(argv[1], O_RDONLY );
    if (fd_input == -1) {
        printf("Cannot open %s!\n",argv[1]);    
        exit(-1);
    }
    fd_output = open(argv[2], O_RDWR | O_CREAT );
    if (fd_output == -1) {
        printf("Cannot open %s!\n",argv[2]);    
        exit(-1);
    }
    if(!stat(argv[1], &st))
        printf("%s size is %ld\n", argv[1], st.st_size);

    fd_read_input = read(fd_input, input, st.st_size);
    size = fd_read_input;
    printf("size = %d\n", size);
    unrle(input, output);

    close(fd_input);
    close(fd_output);
    return 0;
}
